package com.songqi.common.core.config.rest;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import java.net.URI;

public class HttpClientRequestFactory extends HttpComponentsClientHttpRequestFactory {

    public static ThreadLocal<Integer> socketTimeoutThreadLocal = new ThreadLocal<>();

    public static ThreadLocal<Boolean> redirectThreadLocal = new ThreadLocal<>();

    public HttpClientRequestFactory(HttpClient httpClient) {
        super(httpClient);
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        HttpContext context = HttpClientContext.create();
        RequestConfig config = createRequestConfig(getHttpClient());
        Integer socketTimeout = socketTimeoutThreadLocal.get();
        Boolean redirect = redirectThreadLocal.get();
        if (socketTimeout == null) {
            socketTimeout = 10000;
        }
        if (redirect == null) {
            redirect = true;
        }
        RequestConfig.Builder builder = RequestConfig.copy(config);
        builder.setSocketTimeout(socketTimeout);
        builder.setRedirectsEnabled(redirect);
        config = builder.build();
        socketTimeoutThreadLocal.remove();
        redirectThreadLocal.remove();
        context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
        return context;
    }
}
